 package com.album.activity.base; 

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.album.R;
import com.album.activity.MainActivity;
import com.album.activity.MessageDialog;
import com.album.activity.SettingActivity;
import com.album.bean.ErrorInfo;
import com.album.bean.UserInfo;
import com.album.bean.loginInfo;
import com.album.common.Constants;
import com.album.common.Sharevariable;
import com.album.provider.ProviderUtil;
import com.album.task.GetUserInfoTask;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.task.UserLoginTask;
import com.album.utils.AndroidUtils;
import com.album.utils.CommonUtil;
import com.album.utils.JsonUtils;
import com.album.utils.MyLog;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Factory;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 

/**
 * @author Kadar.Li
 * @date 2011-7-5 下午02:09:05 
 * @Description: 
 * @version V1.0 
 */
public class BaseActivity extends Activity{ 

	protected MainActivity mMainActivity; 
	protected DisplayMetrics displayMetrics;
	private OperateHandler handler;
	public final int nitive_back = 111;
	
	private Context context;
	protected Toast toast;
	private ProgressDialog dialog_login; 
	private ProgressDialog dialog_userInfo; 
	protected SharedPreferences ferences = null;
	private static final int LOGIN = 99;
	private static final int LOGIN_SUC = 100;
	private static final int LOGIN_FAIL = 101;
	private final int USER_INFO_SUC=111;
	private final int USER_INFO_FAIL=112;
	private final int TIME_OUT = 113;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header);
		//永远在头部
		displayMetrics = new DisplayMetrics();  
		handler = new OperateHandler();
		
			getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 
			Constants.window_heigt = displayMetrics.heightPixels; 
			Constants.window_width = displayMetrics.widthPixels;
			Constants.m_screenWidth = displayMetrics.widthPixels / 4; 
			Constants.m_screenHeight=displayMetrics.heightPixels;
			ferences = getSharedPreferences(Constants.SYS_PACKAGE,MODE_PRIVATE);
		String imsi = AndroidUtils.getPhoneIMSI(this);
		if(1!=0){
			MyLog.info(getClass(), "==========================");
			setMain();
		}
	}
	
	public void setMain(){
		setContentView(R.layout.login);
		final EditText userEidtText = (EditText)findViewById(R.id.username);
		final EditText pwdEidtText = (EditText)findViewById(R.id.password);
		Button btnLogin = (Button)findViewById(R.id.btn_login);
		Button btnRegister = (Button)findViewById(R.id.btn_register);
		
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//login thread...
				String userName= getEditTextValue(userEidtText);
				String pwd= getEditTextValue(pwdEidtText);
				if(userName!="" && pwd!=""){
					loginthread(userName, pwd);
				}
				else{
					MessageDialog.showToast(BaseActivity.this, false, getRestring(R.string.label_login_error));
				}
			}
		});
		
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//register...
			}
		});
	} 
	private void loginthread(String userName,String pwd){
		dialog_login = ProgressDialog.show(context, "", context.getText(R.string.login_doing), true);
		//userName="18926128667@189.cn";
		//pwd = "";
		//调接口进行登录操作
		String imsi="460036241155921";
		//String imsi = CommonUtil.getIMSI(context);
		final Gson gson = new Gson();
		Task loginTask = new UserLoginTask(context,imsi,userName,pwd,new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
			}
			@Override
			public void CallBack(String rspString) {
				MyLog.info(getClass(), "login resp:"+rspString);
				loginInfo info = gson.fromJson(rspString.toString(), loginInfo.class);
				if(info.getMsg()){
					Message ms = new Message();
					ms.obj = info;
					ms.what = LOGIN;
					handler.sendMessage(ms);
				}else{
					Message ms = new Message();
					ms.obj = info;
					ms.what = LOGIN_FAIL;
					handler.sendMessage(ms);
				}
			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
		});
		loginTask.doTask(loginTask);
	}
	private void getUserInfo(){
		dialog_userInfo = ProgressDialog.show(context, "", context.getText(R.string.userinfo_doing), true);
		//String username="18926128667@189.cn";
		String username = CommonUtil.getUserName(context);
		Task task = new GetUserInfoTask(context,username, new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
				// TODO Auto-generated method stub
			}
			@Override
			public void CallBack(String rspString) {
				if (validateMessage(rspString)) {
					try {
						rspString = "[" + rspString + "]";
						JSONArray array = new JSONArray(rspString);
						JSONObject obj = array.getJSONObject(0);
						if (obj.getBoolean("msg")) {
							UserInfo info = new UserInfo();
							JSONObject res = obj.getJSONObject("data");
							MyLog.info(getClass(), "jsonData:" + res.toString());
							info = (UserInfo) JsonUtils.parseJson2Obj(
									res.toString(), UserInfo.class);
							ProviderUtil.insertOrUpdateUserInfo(context, info);
							Message ms = new Message();
							ms.obj = info;
							ms.what = USER_INFO_SUC;
							handler.sendMessage(ms);
						} else {
							UserInfo info = new UserInfo();
							info.setErrCode(obj.getString("errCode"));
							Message ms = new Message();
							ms.obj = info;
							ms.what = USER_INFO_FAIL;
							handler.sendMessage(ms);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
		});
		task.doTask(task);
	}
	class OperateHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			// 更新界面
		switch (msg.what) {
		/** ------------4x2---------------- **/
		case LOGIN:
			loginInfo info = (loginInfo) msg.obj;
			MyLog.debug(getClass(), info.getErrCode());
			MyLog.debug(getClass(), info.getMsg() + "");
			MessageDialog.showToast(context, true,
					getRestring(R.string.label_login_succend));
			if (dialog_login != null || dialog_login.isShowing())
				dialog_login.dismiss();
			handler.sendEmptyMessage(LOGIN_SUC);
			break;
		case LOGIN_FAIL:
			loginInfo info_fail = (loginInfo) msg.obj;
			MessageDialog.showToast(context, false,
					ErrorInfo.errorMap.get(info_fail.getErrCode()));
			if (dialog_login != null || dialog_login.isShowing())
				dialog_login.dismiss();
			break;
		case LOGIN_SUC: // 登录成功
			MyLog.debug(getClass(), "登录成功");
			//获取用户资料
			getUserInfo();
		case USER_INFO_SUC:
			if (dialog_userInfo != null || dialog_userInfo.isShowing())
				dialog_userInfo.dismiss();
			break;
		case USER_INFO_FAIL:
			UserInfo userinfo_fail = (UserInfo) msg.obj;
			MessageDialog.showToast(context, false,
					ErrorInfo.errorMap.get(userinfo_fail.getErrCode()));
			if (dialog_userInfo != null || dialog_userInfo.isShowing())
				dialog_userInfo.dismiss();
			break;
		case TIME_OUT:
			if (dialog_login != null && dialog_login.isShowing())
				dialog_login.dismiss();
			if (dialog_userInfo != null && dialog_userInfo.isShowing())
				dialog_userInfo.dismiss();
			MessageDialog.showToast(context, false, context.getString(R.string.int_timeout));
			break ;
			}
		}
	}
//	class loginTask extends AsyncTask{ 
//		
//		@Override
//		protected loginInfo doInBackground(Object... params) {
//			// TODO Auto-generated method stub
//			loginInfo info = null;
//			HttpRequest request = new HttpRequest();
//			String strUrl =Config.TyHttp 
//			+Config.TyUserHttp
//			+"login?imsi="+"133001330000"
//			+"&passport="+params[0]
//			+"&passsword="+params[1];
//	        String jsonData = request.sendDataPost(strUrl, null);
//	        if (validateMessage(jsonData)) {
//	        	info = (loginInfo)JsonUtils.parseJson2Obj(jsonData, loginInfo.class); 
//	        }
//	        return info;
//		}
//		
//		@Override
//		protected void onPostExecute(Object result) {
//			// TODO Auto-generated method stub 
//			if(result!=null){
//				loginInfo info = (loginInfo)result;
//				MyLog.debug(getClass(), info.getErrCode());
//				MyLog.debug(getClass(), info.getMsg()+"");
//				if(info.getMsg()){
//					showToast(BaseActivity.this, true, getRestring(R.string.label_login_succend));
//				}else{
//					showToast(BaseActivity.this, false, ErrorInfo.errorMap.get(info.getErrCode()));
//				}
//			}
//			if(dialog!=null || dialog.isShowing())dialog.dismiss();
//			
//		}
//		 
//	}
//	

	/**
	 * 返回结果有效性验证
	 * @param jsonData
	 * @return
	 */
	public boolean validateMessage(String jsonData) {
		// 数据不存在
		if (null == jsonData || "".equals(jsonData)){
			return false;
		}
		return true;
	}
	public Handler baseHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				
				break;

			default:
				break;
			}
		}
	};
	
	//保存用户信息
	private void setUserInfo(String userName,String pwd){
		if(ferences==null)
			ferences = getSharedPreferences(Constants.SYS_PACKAGE,MODE_PRIVATE);
		Editor edit = ferences.edit();
		edit.putString(Constants.SESSION_USER_NAME, userName);
		edit.putString(Constants.SESSION_USER_PASS, pwd);
		edit.commit();
	}

	public String getRestring(int resID){
		return getResources().getString(resID);
	}
	
		
	public final String getEditTextValue(EditText et) {
		if (et == null)
			return null;
		String tmp = "";
		if (et!=null) {
			if(et.getText().toString().trim().length()>0)
				tmp = et.getText().toString().trim();
		}
		return tmp;
	}
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//			return true;
//		}
//		return super.onKeyDown(keyCode, event);
//	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
	}
	public void destroyAll(){
		try {
			ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
			activityManager.restartPackage(getPackageName());
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
			this.finish();
		} catch (Exception e) { }
	}
	/**
	 * 设置MainActivity的引用
	 *
	 * @param instance
	 * @return 
	 */
	public void setMainActivity(MainActivity instance){
		this.mMainActivity = instance;
	}
	 
	
	 @Override  
	    public boolean onCreateOptionsMenu(Menu menu) {  
	           super.onCreateOptionsMenu(menu);  
			     MenuInflater inflater = new MenuInflater(getApplicationContext());  
//			     inflater.inflate(R.menu.options_menu, menu);  
//			     setMenuBackground();  
	        // TODO Auto-generated method stub 15914481012
	           menu.add(0, 1, 1, "设置");
	           menu.add(0, 2, 2, "返回");
	           return true;  
	    }  

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// TODO Auto-generated method stub
			//菜单点击事件
			MyLog.debug(getClass(), "itemID:"+item.getItemId());
			switch (item.getItemId()) {
			case 1:
	        	Intent intet = new Intent();
	        	intet.setClass(this, SettingActivity.class);
	        	startActivityForResult(intet, 1111);
				break;
			case 2:
				break;
			}
			return super.onOptionsItemSelected(item);
		}
		
		protected void setMenuBackground(){ 
		     
		     getLayoutInflater().setFactory( new Factory() { 
		      
		      @Override 
		      public View onCreateView ( String name, Context context, AttributeSet attrs ) { 
		    
		       if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) { 

		      //上面这句不能有改动 
		        
		        try { 

		         LayoutInflater f = getLayoutInflater(); 
		         final View view = f.createView( name, null, attrs );  

		         new Handler().post( new Runnable() { 
		          public void run () { 
		           view.setBackgroundResource( R.drawable.menu_bg); //设置背景为我们自定义的图片 
		          } 
		         } ); 
		         return view; 
		        } 
		        catch (Exception e ) {} 
		       } 
		       return null; 
		      } 
		     }); 
		    } 
//	private void showSettings(){  
//	       
//	     final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);  
//	         settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |  
//	                 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);  
//	           
//	     startActivity(settings);  
//	}  
		public void clearApplicationBitmaplist(List<Bitmap> listBitmap){
	    	if(listBitmap!=null && listBitmap.size()>0)
	    		for(Bitmap bitmap : listBitmap){ 
	    			if(bitmap !=null && bitmap.isRecycled())
	    				bitmap.recycle(); 
						bitmap=null;
	    		}
	    	listBitmap.clear();
	    	listBitmap = null; 
	    }
		
		public void clearBitmapListThread(){
			Thread t = new Thread(){
				@Override
				public void run() {
					// TODO Auto-generated method stub
					clearApplicationBitmaplist(Sharevariable.listBitmap_public);
					clearApplicationBitmaplist(Sharevariable.listBitmap_pwd);
					clearApplicationBitmaplist(Sharevariable.listBitmap_share);
				}
			};
			t.setDaemon(true);
			t.start();
		}
}
